package com.hrt.manage.role.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hrt.base.BaseController;
import com.hrt.bean.ProType;
import com.hrt.bean.ProductInfor;
import com.hrt.bean.Role;
import com.hrt.bean.RoleAccess;
import com.hrt.bean.UserVO;
import com.hrt.bean.UsersInfor;
import com.hrt.bean.ViewResource;
import com.hrt.bean.ViewResourceScopes;
import com.hrt.manage.access.service.AccessService;
import com.hrt.manage.menus.service.ViewResourceService;
import com.hrt.manage.role.service.RoleService;
import com.hrt.manage.sequence.service.SequenceService;
import com.hrt.util.PageUtils;
import com.hrt.util.PinYinUtil;
import com.hrt.util.WebParams;
import com.hrt.util.upload.Plupload;
import com.hrt.util.upload.UploadUtil;
import com.hrt.vo.RoleAccessVO;
import com.sun.mail.iap.Response;

@Controller
@RequestMapping(value = "manage/role")
public class RoleController extends BaseController<Role> {

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private AccessService accService;
	
	@Autowired
	private ViewResourceService viewResourceService;

	private Role role;

	@Autowired
	private SequenceService sequenceService;

	@RequestMapping(value = "/list")
	public ModelAndView list(HttpServletRequest request) {

		ModelAndView view = new ModelAndView();
		view.setViewName("manage/role/list");
		List<Role> resultList = new ArrayList<Role>();
		resultList = roleService.queryByPage(this.getPageIndex(),
				this.getPageSize());

		setTotalCount(roleService.totalCount());
		this.setList(resultList);
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));
		//
		page = this.getPage();
		// view.addObject("proTypes", getProTypes());
		view.addObject("pageResult", page);
		// view.addObject("productStatus", productStatus);
		// request.getSession().setAttribute("pageResult", page);
		return view;
	}

	@RequestMapping(value = "/queryByPage")
	@ResponseBody
	public Map<String, PageUtils<Role>> queryByPage(
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			@RequestParam(value = "roleName", required = false) String roleName,
			HttpServletRequest request) {
		Map<String, PageUtils<Role>> resultMap = new HashMap<String, PageUtils<Role>>();

		if (pageSize == null || "".equals(pageSize)) {
			pageSize = 10;
		}
		if (pageIndex == null || "".equals(pageIndex)) {
			pageIndex = 1;
		}
		setPageIndex(pageIndex);

		setPageSize(pageSize);
		List<Map<String, Object>> conditions = new ArrayList<Map<String, Object>>();
		List<Role> resultList = new ArrayList<Role>();
		setTotalCount(this.roleService.totalCount(null));

		if (roleName == null || "".equals(roleName)) {
			resultList = roleService.queryByPage(getPageIndex(), getPageSize());
		} else {
			resultList = roleService.queryByPage(conditions, pageIndex,
					pageSize);
		}
		setList(resultList);

		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();

		resultMap.put("pageResult", page);
		return resultMap;
	}

	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	@ResponseBody
	public  Long[] delete(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		ModelAndView view = new ModelAndView();

		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
				
			}

		}
		
		this.roleService.deleteById(idArr);
		return idArr;

	}

	@RequestMapping(value = "/add")
	@ResponseBody
	public Map<String, Object> add(HttpServletResponse response,
			HttpServletRequest request) {
		role = new Role();

		Map<String, Object> map = BaseController.transBean2Map(role);

		return map;

	}

	@RequestMapping(value = "/queryRolePinYin")
	@ResponseBody
	public String queryRolePinYin(
			@RequestParam(value = "rName") String roleName,
			HttpServletResponse response, HttpServletRequest request) {
		String pinyin = new String();
		if (roleName != null && !"".equals(roleName)) {
			try {

				roleName = new String(roleName.getBytes("iso-8859-1"), "utf-8");
				if (roleName != null && !"".equals(roleName)) {
					pinyin = PinYinUtil.cn2FirstSpell(roleName);
				}
				String rCode = this.roleService.queryRoleByPinYin(pinyin);
				if (rCode != null) {
					return String.valueOf(Response.BAD);
					// return "数据库中存在相同的角色名字，请重新输入";
				} else {
					return pinyin;
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "系统错误，获取角色编码失败";
			}

		}
		return null;
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void save(@ModelAttribute("roleDetail") Role role,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView model = new ModelAndView();
		System.out.println("save");

		UserVO manager = this.getOnlineManager(request, response);
		if(manager!=null){
		role.setCreator(manager.getLoinName());
		role.setEditor(manager.getLoinName());
		role.setCreateTime(this.roleService.getDate());
		role.setEditTime(this.roleService.getDate());
		this.roleService.saveRole(role);
		}
		try {

			

			response.sendRedirect("list.do");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/saveAccInfor", method = RequestMethod.POST)
	public void saveAccInfor(@ModelAttribute("accDetail") RoleAccessVO roleAcc,
			HttpServletRequest request, HttpServletResponse response)
	{
		List<Long> resList=roleAcc.getResIds();
		Integer scope=roleAcc.getScope();
		Long roleId=roleAcc.getRoleId();
		if(resList!=null && !resList.isEmpty()){
			this.roleService.saveAccInfor(roleId,scope,resList);
		}
		try {
			response.sendRedirect("list.do");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public void update(@ModelAttribute("roleDetail") Role role,
			HttpServletRequest request, HttpServletResponse response) {

		System.out.println("save");

		UserVO manager = this.getOnlineManager(request, response);
		
	   Role oldRole=roleService.getRoleById(role.getId());
	   oldRole.setEditor(manager.getLoinName());
	   oldRole.setrCode(role.getrCode());
	   oldRole.setrName(role.getrName());
	   oldRole.setNote(role.getNote());
	   oldRole.setEditTime(this.roleService.getDate());

		try {

			this.roleService.updateRole(oldRole);

			response.sendRedirect("list.do");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/show")
	@ResponseBody
	public Map show(@RequestParam(value = "id", required = true) Long roleId,
			HttpServletRequest request, HttpServletResponse response) {

		Map map = new HashMap();
		if (roleId != null && !"".equals(roleId)) {
			// Map resultMap=new HashMap<K, V>();
			
			role = this.roleService.getRoleById(roleId);
			if (role != null) {
				map = transBean2Map(role);

			}

		}
		return map;

	}
	
	
	
	@RequestMapping(value = "/queryAccByScope")
	@ResponseBody
	public Map queryAccByScope(
			@RequestParam(value = "roleId", required = true) Long roleId,
			@RequestParam(value = "scope", required = true) Integer scope,
			HttpServletRequest request, HttpServletResponse response){
		Map map = new HashMap();
		List<ViewResource> resultList=new ArrayList<ViewResource>();
		
		List<ViewResource> resList=new ArrayList<ViewResource>();
		scope=0;
		if (roleId != null && !"".equals(roleId)) {
			// Map resultMap=new HashMap<K, V>();
			role = this.roleService.getRoleById(roleId);
			resultList = accService.queryAccByScope(roleId,scope);
			
			if(scope.intValue()==ViewResourceScopes.MANAGE_RESOURCE.intValue()||scope.intValue()==ViewResourceScopes.WEB_RESOURCE.intValue()){
				
				 resList = viewResourceService.listManageMenuns(roleId,scope);
			}
			map.put("accList", resultList);
			map.put("resList", resList);
			map.put("role", role);

		}
		return map;
	}
	
	
	
//	@RequestMapping(value = "/queryAccByRole")
//	@ResponseBody
//	public Map queryAccByRole(@RequestParam(value = "roleId", required = true) Long roleId,
//			HttpServletRequest request, HttpServletResponse response){
//		Map map = new HashMap();
//		List<ViewResource> resultList=new ArrayList<ViewResource>();
//		
//		List<ViewResource> resList=new ArrayList<ViewResource>();
//		
//		if (roleId != null && !"".equals(roleId)) {
//			// Map resultMap=new HashMap<K, V>();
//			role = this.roleService.getRoleById(roleId);
//			resultList = accService.queryAccByRole(roleId);
//			role = this.roleService.getRoleById(roleId);
//			resList = viewResourceService.listManageMenuns(ViewResourceScopes.MANAGE_RESOURCE);
//			map.put("accList", resultList);
//			map.put("resList", resList);
//			map.put("role", role);
//
//		}
//		return map;
//	}

}
